在React中加入 svg 圖檔


Posted by mijouhsieh on 2023-10-03

筆記兩種方法:

  • Part1 絕對路徑載入 svg 圖檔 使用<object>標籤
  • Part2 使用svg library => svg 會被渲染成 React 元件 (效能較優)
  • Part3 絕對路徑載入 svg 圖檔 ** 使用<span>標籤

前提 !!此create-react-app 專案使用絕對路徑:

參考資料:

在專案資料夾內,新建jsconfig.json檔案

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

chatGTP解釋:
絕對路徑設定檔.png


Part1 絕對路徑載入 svg 圖檔

絕對路徑載入svg檔

根路徑是src資料夾,所以svg圖檔路徑從assets開始寫起。避免相對路徑的不易維護寫法。
這邊使用<object>標籤,帶有路徑的變數放在 屬性 data={變數}

import plusIcon from "assets/icons/plus.svg"; 
// import plusIcon from "../../../assets/icons/plus.svg";

Part3 絕對路徑載入 svg 圖檔-使用<span>標籤

react-svg-part3.png


#svg #絕對路徑 #jsconfig.json #absolute path







Related Posts

 # Python 爬取與存取空氣品質 PM2.5 AQI

# Python 爬取與存取空氣品質 PM2.5 AQI

學習 Git - 不小心刪掉的檔案救的回來嗎?

學習 Git - 不小心刪掉的檔案救的回來嗎?

ASP.NET Core Web API 入門教學 - From之常用來源標籤功能用法介紹

ASP.NET Core Web API 入門教學 - From之常用來源標籤功能用法介紹


Comments